package com.ramnight.sql2.component;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ramnight.sql2.ext.name.INameConverter;

public class RecList implements Iterable<Record> {
	
	private List<Record> list;
	
	public RecList(){
		this.list = new ArrayList<>();
	}
	
	public RecList(List<Record> list){
		this.list = list;
	}
	
	/**
	 *  {"id1" : {}, "id2" : {} ...}
	 */
	public JSONObject toJSONObject() {
		JSONObject obj = new JSONObject();
		for(Record rec : list){
			obj.put(rec.getPk().toString(), rec.toJSONObject());
		}
		return obj;
	}

	public JSONArray toJSONArray() {
		JSONArray array = new JSONArray();
		for(Record rec : list){
			array.add(rec.toJSONObject());
		}
		return array;
	}

	public String toJSONString() {
		return toJSONArray().toJSONString();
	}

	public RecList include(String... cols) {
		for(Record rec : list){
			rec.retain(cols);
		}
		return this;
	}

	public RecList exclude(String... cols) {
		for(Record rec : list){
			rec.exclude(cols);
		}
		return this;
	}

	public RecList nameConvert(INameConverter converter) {
		for(Record rec : list){
			rec.nameConvert(converter);
		}
		return this;
	}

	@SuppressWarnings("unchecked")
	public <T> List<T> getPks() {
		List<T> pks = new ArrayList<>();
		for(int i=0; i<list.size(); i++){
			pks.add((T)list.get(i).getPk());
		}
		return pks;
	}
	
	public void add(Record rec){
		list.add(rec);
	}
	
	public Record get(int index){
		return list.get(index);
	}
	
	public List<Record> list(){
		return this.list;
	}
	
	public int size(){
		return list.size();
	}

	@Override
	public Iterator<Record> iterator() {
		return list.iterator();
	}
	
	/**
	 * for group_concat
	 * split "1,2,3,4,5"
	 */
	public RecList toArray(String key){
		for(Record rec : this){
			rec.set(key, rec.getString(key).split(","));
		}
		return this;
	}
}
